package com.bed.lovewithpatientbed.service.impl;

import com.bed.lovewithpatientbed.common.bean.LayUiPageBean;
import com.bed.lovewithpatientbed.common.SoftDelStatus;
import com.bed.lovewithpatientbed.common.params.UserSearchParams;
import com.bed.lovewithpatientbed.dao.UserDao;
import com.bed.lovewithpatientbed.pojo.User;
import com.bed.lovewithpatientbed.pojo.UserExample;
import com.bed.lovewithpatientbed.service.IUserService;
import com.bed.lovewithpatientbed.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author xuxiaoding
 * @version 1.0.0
 * @ClassName UserServiceImpl.java
 * @Description TODO
 */
@Service
@Transactional
public class UserServiceImpl implements IUserService {

    private UserDao userDao;

    @Autowired
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> register(User user) {
        Map<String, Object> msgMap = new HashMap<>();

        // 断言 user != null
        assert user != null;

        // 先查询电话是否已经注册
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUserPhoneEqualTo(user.getUserPhone());
        List<User> userList = userDao.selectByExample(userExample);
        if (userList.size() > 0) {
            msgMap.put("registerResult", false);
            List<String> errorMsg = new ArrayList<>();
            errorMsg.add("该手机号已经被注册");
            msgMap.put("errorMsg", errorMsg);
            return msgMap;
        }

        // 填充注册时间为当前时间
        user.setUserRegisterDate(DateUtil.getCurrentDate());
        // 新用户
        user.setUserTypeId(1);
        // 没有被注册，插入
        int effectedRow = userDao.insert(user);
        msgMap.put("registerResult", effectedRow == 1);

        return msgMap;
    }

    @Override
    public boolean login(User user) {
        return false;
    }

    @Override
    public boolean logout(User user) {
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUserByPrimaryKeySelective(User user) {
        assert user != null;
        int effectedRow = userDao.updateByPrimaryKeySelective(user);

        return effectedRow == 1;
    }

    @Override
    public User retrieveUserById(Integer userId) {
        if (userId == null || userId < 1) {
            return null;
        }

        return userDao.selectByPrimaryKey(userId);
    }

    @Override
    public User retrieveByUserPhone(String userPhone) {
        if (userPhone == null || "".equals(userPhone)) {
            return null;
        }

        UserExample userExample = new UserExample();
        userExample.createCriteria().andUserPhoneEqualTo(userPhone);
        List<User> userList = userDao.selectByExample(userExample);
        if (userList.size() < 1) {
            return null;
        }

        return userList.get(0);
    }

    @Override
    public long retrieveUserCount() {
        return userDao.countByExample(null);
    }

    @Override
    public List<User> retrieveAllUserWithLimit(LayUiPageBean pageBean) {
        System.out.println("UserServiceImpl.retrieveAllUserWithLimit");
        UserExample userExample = new UserExample();
        userExample.setOrderByClause("user_register_date desc");
        userExample.createCriteria().andSoftdelEqualTo(SoftDelStatus.SOFT_DEL_EXIST);

        // 添加分页
        if (pageBean != null && pageBean.getPage() > 0 && pageBean.getLimit() > 0) {
            userExample.setOffset((pageBean.getPage() - 1) * pageBean.getLimit());
            userExample.setLimit(pageBean.getLimit().intValue());
        }
        System.out.println(userExample.getOredCriteria());

        return userDao.selectByExample(userExample);
    }

    @Override
    public long getCountByCondition(UserSearchParams userSearchParams) {
        UserExample userExample = new UserExample();
        appendCriteria(userSearchParams, userExample.createCriteria());

        return userDao.countByExample(userExample);
    }

    @Override
    public List<User> retrieveUserByConditionWithLimit(LayUiPageBean pageBean, UserSearchParams userSearchParams) {
        UserExample userExample = new UserExample();
        // 添加分页
        if (pageBean != null && pageBean.getPage() > 0 && pageBean.getLimit() > 0) {
            userExample.setOffset((pageBean.getPage() - 1) * pageBean.getLimit());
            userExample.setLimit(pageBean.getLimit().intValue());
        }
        // 添加搜索条件
        UserExample.Criteria criteria = userExample.createCriteria();
        appendCriteria(userSearchParams, criteria);
        // 按注册日期倒序
        userExample.setOrderByClause("user_register_date desc");

        return userDao.selectByExample(userExample);
    }

    /**
     * @title appendCriteria
     * @description 根据 userSearchParams 给 Criteria 追加条件
     * @author xuxiaoding
     * @param userSearchParams 条件检索条件
     * @param criteria UserExample.Criteria
     */
    private void appendCriteria(UserSearchParams userSearchParams, UserExample.Criteria criteria) {
        if (criteria != null) {
            // 查询没被删除的数据
            criteria.andSoftdelEqualTo(SoftDelStatus.SOFT_DEL_EXIST);
            // 追加搜索条件
            if (userSearchParams != null) {
                // 手机号
                if (userSearchParams.getUserPhone() != null && !"".equals(userSearchParams.getUserPhone())) {
                    criteria.andUserPhoneEqualTo(userSearchParams.getUserPhone());
                }
                // 用户类型
                if (userSearchParams.getUserTypeId() != null && userSearchParams.getUserTypeId() > 0){
                    criteria.andUserTypeIdEqualTo(userSearchParams.getUserTypeId());
                }
                // 性别
                if (userSearchParams.getUserSex() != null && !"".equals(userSearchParams.getUserSex())) {
                    criteria.andUserSexEqualTo(userSearchParams.getUserSex());
                }
                // 注册时间范围
                if (userSearchParams.getUserRegisterStartDate() != null
                        && userSearchParams.getUserRegisterEndDate() != null) {
                    criteria.andUserRegisterDateBetween(userSearchParams.getUserRegisterStartDate(),
                            userSearchParams.getUserRegisterEndDate());
                }
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean softDeleteUser(Integer userId) {
        User user = new User();
        user.setUserId(userId);
        user.setSoftdel(SoftDelStatus.SOFT_DEL_DELETED);
        return updateUserByPrimaryKeySelective(user);
    }

    @Override
    public boolean batchSoftDeleteUser(Integer[] userIdList) {
        if (userIdList == null || userIdList.length < 1) {
            return false;
        }
        User user = new User();
        user.setSoftdel(SoftDelStatus.SOFT_DEL_DELETED);
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUserIdIn(Arrays.asList(userIdList));
        int effectedRows = userDao.updateByExampleSelective(user, userExample);

        return effectedRows == userIdList.length;
    }
}
